﻿package com.urbansquall.echo
{
	import com.urbansquall.echo.ChannelWrapper;
	import com.urbansquall.echo.GroupedSound;
	import com.urbansquall.echo.SoundGroup;
	import com.urbansquall.echo.WrapperEvent;
	import flash.media.Sound;
	
	/**
	 * Loop is a class that is basically designed for handling background music. 
	 * @author Marshall Powers
	 */
	public class Loop 
	{
		private var m_wrapper : ChannelWrapper;
		private var m_groupedSound : GroupedSound;
		private var m_volume : Number;
		
		public function Loop(a_group : SoundGroup, a_sound : Sound) 
		{
			m_groupedSound = new GroupedSound(a_group, a_sound);
			m_volume = 1.0;
		}
		
		public function play() : void
		{
			if (m_wrapper != null)
			{
				stop();
			}
			m_wrapper = m_groupedSound.play(0, int.MAX_VALUE);
			m_wrapper.localVolume = m_volume;
			if (m_wrapper != null)
			{
				m_wrapper.addEventListener(WrapperEvent.SOUND_COMPLETE, wrapperPlaybackEnded);
				m_wrapper.addEventListener(WrapperEvent.SOUND_STOPPED, wrapperPlaybackEnded);
			}
		}
		
		private function wrapperPlaybackEnded(a_event : WrapperEvent) : void
		{
			m_wrapper.removeEventListener(WrapperEvent.SOUND_COMPLETE, wrapperPlaybackEnded);
			m_wrapper.removeEventListener(WrapperEvent.SOUND_STOPPED, wrapperPlaybackEnded);
			m_wrapper = null;
		}
		
		public function stop() : void
		{
			m_wrapper.stop();
		}
		
		public function isPlaying() : Boolean
		{
			return m_wrapper != null;
		}
		
		public function get volume() : Number
		{
			if (m_wrapper != null)
			{
				return m_wrapper.localVolume;
			}
			return 0.0;
		}
		
		public function set volume(a_volume : Number) : void
		{
			m_volume = a_volume;
			if (m_wrapper != null)
			{
				m_wrapper.localVolume = m_volume
			}
		}
	}
}